package com.hs.jhzd.controller;

import java.util.List;
import java.util.Optional;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hs.jhzd.entity.EquipmentModule;
import com.hs.jhzd.repository.EquipmentModuleRepository;
import com.hs.jhzd.service.message.NoticeProducer;
import com.hs.jhzd.service.message.SysNotice;

@Controller
@RequestMapping("/em")
public class EquipmentModuleController {

  @Autowired
  private EquipmentModuleRepository repository;

  @Autowired
  @Lazy
  private NoticeProducer noticeProducer;

  @Value("${jsbh}")
  private String jsbh;

  @RequestMapping("/admin/main")
  private String mainPage(Model model, String jsbh) {
    if (StringUtils.isBlank(jsbh) || StringUtils.equals(jsbh, "null")) {
      return "redirect:/content/admin/main?jsbh=" + this.jsbh;
    }
    model.addAttribute("equipmentModules", repository.findByJsbhOrderByCode(jsbh));
    model.addAttribute("jsbh", jsbh);
    return "equipment-module-list";
  }

  @RequestMapping("/findByJshb")
  @ResponseBody
  private List<EquipmentModule> findByJshb(String jsbh) {
    return repository.findByJsbhOrderByCode(jsbh);
  }

  @RequestMapping("/findById")
  @ResponseBody
  private EquipmentModule findById(Long id) {
    Optional<EquipmentModule> equipmentModule = repository.findById(id);
    return equipmentModule.isPresent() ? equipmentModule.get() : null;
  }

  @RequestMapping("/findVisibleByJsbh")
  @ResponseBody
  private List<EquipmentModule> findVisibleByJsbh(String jsbh) {
    return repository.findVisibleByJsbh(jsbh);
  }

  @RequestMapping("/save")
  @ResponseBody
  public String save(EquipmentModule equipmentModule) {
    repository.save(equipmentModule);
    return "success";
  }

  @RequestMapping("/delete")
  @ResponseBody
  public boolean
  delete(@RequestParam(required = true) Long id) {
    repository.deleteById(id);
    return true;
  }

  @RequestMapping("/sendModuleUpdateRemind")
  @ResponseBody
  public boolean sendModuleUpdateRemind(@RequestParam(required = true) String prisonId) {
    if (noticeProducer == null) {
      return false;
    }
    SysNotice sysNotice = new SysNotice();
    sysNotice.setType("module_update");
    noticeProducer.sendMessage("equipment.all", sysNotice);
    return true;
  }
}
